﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Application.Impl
{
    using EC.Application.Interface;

    using EC.Entity;
    using EC.Entity.Query;
    using EC.Entity.Response.Log;

    /// <summary>
    /// 日志
    /// </summary>
    public class LogServiceImpl: LogService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public LogServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<LogQueryResponse> GetPager(LogQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,Level,Source,Message,Exception,Ip,CreatedBy,CreatedDate";
            var tableName = "log";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";

            #region 条件
            //if (!string.IsNullOrEmpty(query.Name))
            //{
            //    where += string.Format(" And Name like'%{0}%'", query.Name);
            //}
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<LogQueryResponse>();

                return new PagedList<LogQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }
    }
}
